//
//  POSProcess.m
//  HPZZTong
//
//  Created by WenJun on 14-7-8.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "POSProcess.h"
#import "HPSwiperService.h"
#import "ProcessEncoder.h"
#import "POSUIEngine.h"
#import "CategoryUtil.h"

static __weak POSProcess * weakSelf = nil;

@interface POSProcess()
{
    SwiperComplete _actionCallBack;
    BOOL _stoped;
}

@property (strong,nonatomic) ProcessEncoder * encoder;

@property (strong,nonatomic) NSString * plainAccount;

@property (readonly,nonatomic) NSString * plainMac;

@property (strong,nonatomic) NSString * plainPin;

@end

@implementation POSProcess

- (void)beginWithDelegate:(id)delegate
{
    [weakSelf clear];
    weakSelf = self;
    _actionCallBack = ^(HPSwiperResult *swiperResult)
    {
        [weakSelf dealResult:swiperResult];
    };
    _delegate = delegate;
    if (!_uiDelegate)
    {
        _uiDelegate = delegate;
    }
    [SwiperService startProcess:self];
}

- (void)continueAction
{
    if (_stoped)
    {
        [self beginAction:_currentAction + 1];
        _stoped = NO;
    }
}

- (void)beginAction:(SwipeAction)action
{
    if (action == SwipeActionSwipe)
    {
        [self swipe];
    }
    else if (action == SwipeActionInputPin)
    {
        [self inputPin];
    }
    else if (action == SwipeActionEncrypt)
    {
        [self encrypt];
    }
    else if (action == SwipeActionCalMac)
    {
        [self calMac];
    }
}

- (void)start
{
    _factor = [SwiperService resetFactor];
    _time = [_factor substringToIndex:14];
    _csn = SwiperService.csn;
    [self beginAction:SwipeActionSwipe];
}

- (void)swipe
{
    if (_currentAction == SwipeActionNone)
    {
        [_uiDelegate notifySwipe:self];
    }
    _currentAction = SwipeActionSwipe;
    [SwiperService doSwiper:_actionCallBack];
}

- (void)reSwipe
{
    [self swipe];
}

- (void)inputPin
{
    _currentAction = SwipeActionInputPin;
    if ([_currentSwiper canInputPin])
    {
        [_uiDelegate notifyInputPin:self appInput:NO];
        [SwiperService doInputPwdWithAmount:_plainAmount complete:_actionCallBack];
    }
    else
    {
        [_uiDelegate notifyInputPin:self appInput:YES];
    }
}
//IC卡EMV交易流程
- (void)doEMV
{
    [_currentSwiper emv:self complete:^(HPSwiperResult *swiperResult) {
        if (swiperResult.isSuccess)
        {
            [self encryptPin];
        }
        else
        {
            [self dealResult:swiperResult];
        }
    }];
}
- (void)encryptPin{
    [_currentSwiper encryptPin:_plainPin factor:_factor complete:^(HPSwiperResult *swiperResult) {
        if (swiperResult.isSuccess)
        {
            [self setValue:swiperResult.value forKeyPath:@"encPin"];
            [self encryptData];
        }
        else
        {
            [self dealResult:swiperResult];
        }
    }];
}

- (void)startEmvOrEncrypt{
    if (_icMode && [NSString isNilOrEmpty:_swipeInfo.dcData])
    {
        [self doEMV];
    }
    else
    {
        [self encryptData];
    }
}

- (void)encryptData{
    _encoder = [[ProcessEncoder alloc] initWithProcess:self];
    [_encoder encyptKeyData];
}
- (void)encrypt
{
    _currentAction = SwipeActionEncrypt;
    _plainAccount = _swipeInfo.plainAccount;
    
    [self startEmvOrEncrypt];
//    [_encoder start];
}

- (NSString *)joinMac
{
    return [_encoder joinMac];
}

- (void)calMac
{
    _currentAction = SwipeActionCalMac;
    _plainMac = [self joinMac];
    [_encoder calMac];
}

- (void)dealResult:(HPSwiperResult *)result
{
    if (result.isCanceld || result.code == HPSwiperResultNotConnected)
    {
        [self finishedWithResult:result];
        return;
    }
    if (result.code == HPSwiperResultSelectApplication){
        [self notifySelectApp:result];
        return;
    }
    if (!result.isSuccess)
    {
        if (!_swipeInfo)
        {
            [self notifyReSwipe:result];
        }
        else
        {
            [self finishedWithResult:result];
        }
    }
    else if (_currentAction == SwipeActionSwipe)
    {
        _swipeInfo = result.value;
        [self didReceiveSwipeInfo];
    }
    else if (_currentAction == SwipeActionInputPin) //刷卡信息最迟在输入完密码之后可以获取到
    {
        if (!_swipeInfo)//ic刷卡器输入完密码之后获取ic卡信息,部分ic卡不需要输入密码可以获取到ic卡信息
        {
            _swipeInfo = result.value;
            _encPin = _swipeInfo.encPin;
            [self continueWithSwipeInfo];
        }
        else
        {
            _encPin = result.value;
        }
        if (!_stoped)
        {
            if (_encPin.length > 0)
            {
                if ([self continueAfterPwdInput])
                {
                    [self beginAction:SwipeActionEncrypt];
                }
            }
            else
            {
                _currentAction = SwipeActionSwipe;
                [self beginAction:SwipeActionInputPin];
            }
        }
    }
    else if (_currentAction == SwipeActionEncrypt)
    {
        [self beginAction:SwipeActionCalMac];
    }
    else if (_currentAction == SwipeActionCalMac)
    {
        _encMac = result.value;
        [self finishedWithResult:result];
    }
}

- (void)didReceiveSwipeInfo
{
    _icMode = _swipeInfo.isICMode;
    if ([self continueWithSwipeInfo])
    {
        if (_encPin.length == 0)
        {
            [self beginAction:SwipeActionInputPin];
        }
        else
        {
            [self beginAction:SwipeActionEncrypt];
        }
    }
}

- (BOOL)continueWithSwipeInfo
{
    if ([_delegate respondsToSelector:@selector(process:didGetSwipeInfo:)])
    {
        _stoped = ![_delegate process:self didGetSwipeInfo:_swipeInfo];
        return !_stoped;
    }
    return YES;
}

- (BOOL)continueAfterPwdInput
{
    if ([_delegate respondsToSelector:@selector(inputPwdFinished:)])
    {
        _stoped = ![_delegate inputPwdFinished:self];
        return !_stoped;
    }
    return YES;
}

- (void)notifySelectApp:(HPSwiperResult *)result{
    if ([_delegate respondsToSelector:@selector(selectApplication:result:)]) {
        [_delegate selectApplication:self result:result];
    }else{
        NSArray* array = (NSArray*)result.value;
        
        NSMutableArray* mutArray = [NSMutableArray array];
        
        for (int i = 0; i<array.count; i++) {
            NSString* strData = [array objectAtIndex:i];
            if (![NSString isNilOrEmpty:strData]) {
                
                NSString* strTemp = [strData uppercaseString];
                NSString* strName = nil;
                
                NSRange range = [strTemp rangeOfString:@"CREDIT"];
                if (range.length != 0) {
                    strName = @"信用卡";
                }
                range = [strTemp rangeOfString:@"DEBIT"];
                if (range.length != 0) {
                    strName = @"借记卡";
                }
                
                range = [strTemp rangeOfString:@"JETCO AID"];
                if (range.length != 0) {
                    strName = @"银都卡";
                }
                range = [strTemp rangeOfString:@"PBOC"];
                if (range.length != 0) {
                    strName = @"PBOC";
                }
                if (![NSString isNilOrEmpty:strName]) {
                    [mutArray addObject:@[strName,strData,[NSNumber numberWithInt:i]]];
                }
            }
        }

        [POSUIENG processSelectApp:mutArray];
    }
}
- (void)notifyReSwipe:(HPSwiperResult *)result
{
    if ([_uiDelegate respondsToSelector:@selector(notifyReSwipe:result:)])
    {
        [_uiDelegate notifyReSwipe:self result:result];
    }
    else
    {
        [self reSwipe];
    }
}

- (void)icQuestInputPin
{
    _icMode = YES;
    _currentAction = SwipeActionInputPin;
    [_uiDelegate notifyInputPin:self appInput:![_currentSwiper canInputPin]];
}

- (void)pinInputed:(NSString *)plainPin
{
    if (!_swipeInfo)
    {
        [SwiperService doInputICPin:plainPin complete:_actionCallBack];
    }
    else
    {
        if (_swipeInfo.dcData.length == 0 && _icMode)
        {
            _plainPin = plainPin;
            if ([self continueAfterPwdInput])
            {
                [self beginAction:SwipeActionEncrypt];
            }
        }
        else
        {
            [SwiperService doEncyptPin:plainPin complete:_actionCallBack];
        }
    }
}

- (void)finishedWithResult:(HPSwiperResult *)result
{
    [self.delegate process:self finishedWithResult:result];
    [self clear];
}

- (void)clear
{
    [SwiperService cancelSwiperOperation];
    _actionCallBack = nil;
    weakSelf = nil;
    _encoder = nil;
}

@end
